<template>
  <div>
    <!-- 内容 -->
    <slot/>
    <div ref='loadingTarget' class='h-6 py-4'>
      <!-- 加载更多 -->
      <m-svg-icon class='w-4 h-4 mx-auto animate-spin' name='infinite-load' v-show='loading'
      ></m-svg-icon>
      <!-- 没有更多数据 -->
      <p v-if='isFinished'
         class='text-center text-base text-zinc-400'
      >
        已经没有更多数据
      </p>
    </div>
  </div>
</template>

<script setup>
import { useIntersectionObserver, useVModel } from '@vueuse/core'
import { ref, watch } from 'vue'

const props = defineProps({
  // 是否处于加载状态
  modelValue: {
    type:Boolean,
    required:true
  },
  // 数据是否全部加载完成
  isFinished: {
    type:Boolean,
    required:true
  }
})
const emits = defineEmits(['onLoad','update:modelValue'])

// 处理 loading 状态
const loading = useVModel(props)

const loadingTarget = ref(null)
// 记录当前是否在底部
const targetIsIntersecting = ref(false)
useIntersectionObserver(loadingTarget,([{ isIntersecting }]) => {
  emitLoad()
  targetIsIntersecting.value = isIntersecting
})

/**
 * 触发 load 事件
 */
const emitLoad = () => {
  setTimeout(() => {
    // 当加载更多的视图可见时，处理加载更多的逻辑
    if (targetIsIntersecting.value && !loading.value && !props.isFinished) {
      emits('onLoad')
      loading.value = true
    }
  },100)
}

watch(loading,emitLoad)
</script>

<style lang='scss' scoped></style>
